package com.dy.org.service.impl;

import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.basic.util.*;
import com.dy.org.domain.Employee;
import com.dy.org.domain.Shop;
import com.dy.org.domain.ShopAuditLog;
import com.dy.org.dto.EmpDto;
import com.dy.org.dto.ShopAuditLogDto;
import com.dy.org.dto.ShopDto;
import com.dy.org.mapper.EmployeeMapper;
import com.dy.org.mapper.ShopAuditLogMapper;
import com.dy.org.mapper.ShopMapper;
import com.dy.org.service.IShopService;
import com.dy.org.vo.ShopVO;
import com.dy.user.domain.Logininfo;
import com.dy.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dayong
 * @since 2023-02-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper empMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 商家入驻
     * @param shopDto
     */
    @Override
    public void settlement(ShopDto shopDto) {
        // 对象是否为空
        // 手机号是否合法
        // 1. 两次密码是否相同
        verification(shopDto);

        // 数据保存到数据库
        // 添加商家但是admin_id值为空
        addShopAndEmp(shopDto);

    }

    /**
     * 商家审核
     * @param dto
     */
    @Override
    public void audit(ShopAuditLogDto dto) throws Exception {
        // 1.state状态的修改 可以根据dto里面的shopId查询商家的信息
        Shop shop = shopMapper.findById(dto.getShopId());
        // 1.1 待激活  state是3   upOrPass为2的话就是待激活的状态  upOrPass为1的话为驳回
        if (dto.getUpOrPass() == 2){
            shop.setState(3);
            shopMapper.update(shop);
            String text = "<h1>恭喜你审核通过：请点击下方链接激活店铺：</h1>" +
                    "http://localhost:8080/shop/audit/jihuo/"+dto.getShopId();
            String people="1504842731@qq.com";
            SendEmailUtil.send(text,people);
        } else {
            shop.setState(2);
            shopMapper.update(shop);
            // 1.创建复杂邮件对象  发送邮件
            String text = "<h1>吊毛审核不过：请点击下方链接重新审核：</h1>"+
                    "                    http://localhost:8081/#/registerAgain?"+dto.getShopId();
            String people="1504842731@qq.com";
            SendEmailUtil.send(text,people);
        }
        // 2.保存日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditId(1);
        shopAuditLog.setShopId(dto.getShopId());
        shopAuditLog.setNote(dto.getNote());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLogMapper.add(shopAuditLog);


    }

    @Override
    public void updateState(Long id) {
        shopMapper.updateState(id);
    }

    /**
     *   店铺柱状图
     * @return
     */
    @Override
    public Map<String, Object> loadShopEchartsData() {
        // 1.得到报表数据
        List<ShopVO> shopVos = shopMapper.loadShopEchartsData();

        List<Integer> x = shopVos.stream().map(ShopVO::getState).collect(Collectors.toList());

        List<Integer> y = shopVos.stream().map(ShopVO::getCountNum).collect(Collectors.toList());

        HashMap<String, Object> data = new HashMap<>();
        data.put("x",x);
        data.put("y",y);
        return data;
    }

    /**
     * 执行添加
     * @param shopDto
     */
    private void addShopAndEmp(ShopDto shopDto) {
        Shop shop2 = shopDto.getShop();
        shopMapper.add(shop2);

        // 添加用户
        Employee emp1 = shopDto.getEmp();
        String password = emp1.getPassword();
        String salt = StrUtils.getRandomString(6);
        String passwordMd5 = MD5Utils.encrypByMd5(salt + password);

        // 添加用户表
        emp1.setSalt(salt);
        emp1.setPassword(passwordMd5);
        // 添加logininfo表
        Logininfo logininfo = new Logininfo();
        logininfo.setType(0);
        BeanUtils.copyProperties(emp1,logininfo);
        logininfoMapper.add(logininfo);

        emp1.setShopId(shop2.getId());
        emp1.setLogininfoId(logininfo.getId());
        empMapper.add(emp1);

        // 添加商家的admin_id
        Shop shop = new Shop();
        shop.setId(shop2.getId());
        shop.setAdminId(emp1.getId());
        shopMapper.update(shop);
    }

    /**
     * 校验数据
     * @param shopDto
     */
    private void verification(ShopDto shopDto) {
        EmpDto empDto = shopDto.getAdmin();
        if (!empDto.getPassword().equals(empDto.getComfirmPassword())){
            throw new BusinessException("两次密码不一致");
        }
        // 2. 商家是否存在
        if (null != shopMapper.findByName(shopDto.getName())){
            throw new BusinessException("商家已存在,滚去登录");
        }
        // 3. 管理员是否只管理一个商家
        Employee employee = empMapper.findByName(empDto.getUsername());
        if (null != employee && null != employee.getShopId()){
            // 通过emp的id查询adminID是否有信息
            Shop shop = shopMapper.findAdminIdById(employee.getId());
            if (shop != null){
                throw new BusinessException("该用户已经是一个商家的管理员");
            }
        }
        // 4. 百度AI校验
        // 图片是否为违规
//        String str="";
//        Boolean aBoolean = BaiduAuditUtils.ImgCensor(shopDto.getLogo());
//        if (!aBoolean){
//            throw new BusinessException("图片很奈斯，请私发");
//        }
//        // 名字是否违规
//        Boolean aBoolean1 = BaiduAuditUtils.TextCensor(shopDto.getName());
//        if (!aBoolean1){
//            throw new BusinessException("商家名称很敏感，要喷了!!");
//        }
// 倒三角  套路：
        // 先获取到父级的集合
        // 根据父级的id集合查询出来所有的子级集合
        // 将子级集合根据父级的id进行分组 转成map
        // 遍历父级集合 使用map.get(父级的id)
        // 将子级放入到父级
    }
}
